<template>
	<!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
	<a-drawer v-model:open="visible" ref="employeeDetailModalRef" class="edit-drawer modal-fixed-bottom"
		root-class-name="root-customer-drawer" width="800px" :closable="false" @close="onClose">
		<div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
		<div class="modal-header">{{ title }}</div>
		<a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol">

			<div style="margin-bottom: 10px;color: green;display: flex;">
				<p style="width: 4px;height: 26px;background: green;"> </p>
				<p style="font-size: 18px;margin-left:10px">Update the firmware</p>
			</div>

			<a-form-item label="FTP URL" name="ftp">
				<a-input allow-clear v-model:value="formState.ftp"
					placeholder="ftp://Account:Password@192.168.1.5:21/file.zip" />
				<p style="color: gray;">For Example：ftp://Account:Password@192.168.1.5:21/file.zip</p>
			</a-form-item>

			<div style="text-align: center;margin-bottom: 10px;">
				<a-button @click="OTA('curr_ftp')" type="primary">{{ $t('self.businessCharging.tips22') }}</a-button>
				<a-button @click="OTA('all_ftp')" style="margin-left: 10px;" type="primary"
					danger>{{ $t('self.businessCharging.tips23') }}</a-button>
			</div>


			<div style="margin-bottom: 10px;color: green;display: flex;">
				<p style="width: 4px;height: 26px;background: green;"> </p>
				<p style="font-size: 18px;margin-left:10px">Update the large advertising screen</p>
			</div>

			<a-form-item :label="$t('self.businessStation.modal.col10')" name="">
				<a-upload v-model:file-list="uploadParams.pic2" name="file" class="uploader-wrapper1"
					list-type="picture-card" :show-upload-list="false" :headers="uploadParams.header"
					:action="uploadParams.url" :data="uploadParams.data" :on-success="handleSuccess"
					@change="handleUploadChange">

					<div class="base-flex base-columns base-align-items-center base-justify-content-center">
						<!-- 			           <plus-outlined class="base-f20 gui-color-grey2" />
			           <div class="ant-upload-text gui-color-grey base-mt10">Upload</div> -->
						<img src="@/assets/homer.png">
					</div>

				</a-upload>

				<div class="gui-color-grey2">{{ $t('self.operators.tips38') }}：MP4 OR JPG/PNG，100M</div>


				<div class="base-flex  base-align-items-left base-justify-content-left">

					<div v-for="pics in allAdv">
						<div
							style="width: 100px;text-align: center;margin-top: 10px;height: 100px;position: relative;margin-bottom: 10px;margin-right: 10px;">
							<p style="margin-bottom: 0px;" v-if="pics.indexOf('.jpg')!=-1||pics.indexOf('.png')!=-1">
								<img :src="pics" style="width: 100px;height: 100px;margin-bottom: 0px;"></img>
							</p>
							<p v-else>
								<img src="@/assets/homer.png" style="width: 100px;height: 100px;">
							</p>
							<p class="del-box">
								<img @click="deletePileAdv(pics)" :lang="pics" src="@/assets/delete.png"></img>
							</p>
						</div>
					</div>

				</div>

				<div style="margin-top: 10px;">
					<a-col class="base-flex base-rows">
						<a-button @click="OTA('curr_adv')"
							type="primary">{{ $t('self.businessCharging.tips22') }}</a-button>
						<a-button @click="OTA('all_adv')" style="margin-left: 10px;" type="primary"
							danger>{{ $t('self.businessCharging.tips23') }}</a-button>
					</a-col>

				</div>
			</a-form-item>

			<div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
				<!--
				<a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
				-->
				<a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
			</div>

		</a-form>

	</a-drawer>
</template>

<script setup>
	import {
		computed,
		getCurrentInstance,
		onMounted,
		ref
	} from 'vue'
	import {
		message
	} from 'ant-design-vue'
	import chooseAreaForLocal from '@/components/choose/choose-area-for-local.vue'
	import config from "@/config"
	import tool from '@/utils/tool';
	import {
		Header
	} from 'ant-design-vue/es/layout/layout';

	const {
		proxy
	} = getCurrentInstance()
	const $TOOL = proxy.$TOOL
	const $API = proxy.$API
	const $T = proxy.$t
	const emit = defineEmits(['close', 'ok'])

	const visible = ref(false)
	// 模式，add新增，show查看，edit编辑
	const mode = ref('edit')
	const labelCol = {
		style: {
			width: '230px',
		},
	};
	const wrapperCol = {
		span: 16,
	};
	const title = ref('')
	const formState = ref({
		"id": '',
		"stationId": "", // 站点id
		"policyId": "", // 资费id
		"pileName": "", // 充电桩名称
		"pileSeri": "", // 桩序列号
		"pileType": null, // 桩类型，直流还是交流
		"chargeInterface": [], // 充电接口，Type 2,SAE J1772 (2个用逗号隔开，我需要改下接口改成字符串)
		"chargePilePowerLow": '', // 功率
		"chargePilePowerMax": '', // 最大功率
		"orgId": "", // 运营商id
		"pileNo": "", // 充电桩总数
		"gunNum": "", // 枪数量，添加桩数量
		"appNode": "1", // 前置服务
		"agreement": 0,
		"adv": "",
		'ftp': "",
	})
	const areaArr = ref([]) // 省市区的集合
	const orgOptions = ref([])
	const allAdv = ref([])
	let token = tool.cookie.get(config.TOKEN_KEY);
	//	console.log('token', token)
	//	 console.log('token2', config.TOKEN_PREFIX + token)
	var uploadParams;

	const formRules = ref({
		orgId: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessStation.modal.col3'),
			trigger: 'change'
		}],
		stationName: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips1'),
			trigger: 'change'
		}],
		stationArea: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col4'),
			trigger: 'change'
		}],
		stationAreaDetail: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col5'),
			trigger: 'change'
		}],
		longitude: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips3'),
			trigger: 'change'
		}],
		latitude: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips4'),
			trigger: 'change'
		}],
		tariffPolicy: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col6'),
			trigger: 'change'
		}],
		mobile: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col7'),
			trigger: 'change'
		}],
		operatingStatus: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.modal.col8'),
			trigger: 'change'
		}],
		supportingFacilities: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.modal.col14'),
			trigger: 'change'
		}],
	})

	onMounted(async () => {
		orgOptions.value = await proxy.getOrgSelectList(true)
	})


	// response参数包含服务器返回的数据
	//console.log('服务器返回:', response);
	// file参数包含上传文件信息
	//console.log('当前文件:', file);
	// fileList参数包含所有已上传文件
	//console.log('文件列表:', fileList);

	const handleUploadChange = (info) => {
		console.log(info);
		console.log(info.fileList);
		console.log(info.fileList.length);
		if (info.file.type != 'video/mp4' && info.file.type != 'image/jpeg' && info.file.type != 'image/png') {
			message.error($T('self.message.fileErr'))
			return false;
		} else if (info.file.type == 'video/mp4' && info.fileList.length > 1) {
			message.error($T('self.message.fileOne'))
			return false;
		} else if (info.file.type != 'video/mp4') {
			for (let i = 0; i < info.fileList.length; i++) {
				const val = info.fileList[i];
				if (val.type != 'image/jpeg' && val.type != 'image/png') {
					message.error($T('self.message.fileJPG'))
					return false;
				}
			}
			//uploadParams.listType='picture-card‌';
		} else {
			//	uploadParams.listType='text';
		}
		if (info.file.status !== 'uploading') {
			console.log(info.file, info.fileList);
		}
		if (info.file.status === 'done') {
			var res = info.file.response;
			if (res.code == 200) {
				//	message.success(`${info.file.name} file uploaded successfully`);
			} else {
				message.error(`${info.file.name} file upload failed.(` + res.msg + `)`);
			}

		} else if (info.file.status === 'error') {
			message.error(`${info.file.name} file upload failed.`);
		}
	}



	const onSubmit = (values) => {
		const params = {
			...formState.value
		}
	}

	const onReset = () => {
		// 清空内容
		areaArr.value = []
		allAdv.value = []
		formState.value = {
			id: '',
			orgId: null,
			stationName: '',
			stationProvince: '',
			stationCity: '',
			stationArea: '',
			stationAreaDetail: '',
			longitude: '',
			latitude: '',
			tariffPolicy: '',
			mobile: '',
			operatingStatus: 0,
			chargeInterface: [],
			characteristic: [], //提供的服务
			supportingFacilities: 0,
		}
	}

	const onClose = () => {
		onReset()
		visible.value = false
		emit('close')
	}

	const add = () => {
		mode.value = 'add'
		title.value = $T('self.businessCharging.tips20')
		visible.value = true
	}

	const edit = (record) => {

		mode.value = 'edit'
		// 克隆存在的键
		console.log(record);
		//console.log(record.pileName);
		$TOOL.array.cloneExistKey(formState.value, record)
		//   var advs=record.adv;
		//   console.log(advs);
		//  var pics=[];
		//  var listType='picture-card‌'
		//  if(typeof(advs)!='undefined'&&advs!=""&&advs!=null){
		//  	var ts=advs.split(",");
		// 	for (let i = 0; i < ts.length; i++) {
		// 		var t =`${ config.static_URL }/uploadFile/adv/`+ts[i];
		// 		console.log(t);
		// 		pics[i]=t;
		// 		if(ts[i].indexOf('.jpg')||ts[i].indexOf('.png')){
		// 			listType="text";
		// 		}
		// 	}
		//  }

		//console.log(pics);
		// allAdv.value=pics;
		uploadParams = ref({
			url: `${ config.API_URL }/admin/uploadFile`,
			header: {
				key: token
			},
			data: {
				id: formState.value.id,
				stationId: formState.value.stationId,
				type: 'adv'
			},
			listType: 'picture-card‌',
			pic1: [], // 场站图片，多张
			pic2: [], // 广告图，多张
		})

		if (typeof(formState.value.pileName) != 'undefined') {
			title.value = $T('self.businessCharging.tips20') + '：' + formState.value.pileName
		} else {
			title.value = $T('self.businessCharging.tips20')
		}
		visible.value = true

		// if (formState.value.orgId) {
		// 	getTariffPolicy()
		// }
		getPileAdv('');
	}

	const handleSuccess = (response, file, fileList) => {
		console.log('服务器返回:', response);
		message.loading($T('self.businessStation.tips15'))
		if (response.code == 200) {
			getPileAdv('');
			console.log(allAdv);
		}
	}
	const deletePileAdv = (data) => {
		// data=data.replace(`${ config.static_URL }`,"");
		data = data.substring(data.lastIndexOf('/') + 1, data.length);
		var params = {
			"id": formState.value.id,
			'adv': data
		}
		console.log(params);
		$API.backend.businessCharging.deletePileAdv.post(params).then(res => {
			const {
				objData,
				code
			} = res
			console.log(objData, code);
			if (code == 200) {
				getPileAdv('');
			} else {
				// message.error($T('self.message.error'))
				message.error(err.msg);
			}
		}).catch(err => {
			// message.error($T('self.message.error'))
			message.error(err.msg);
		})
	}
	const getPileAdv = (data) => {
		//data=data.replace(`${ config.static_URL }`,"");
		var params = {
			"id": formState.value.id
		}
		console.log(params);
		$API.backend.businessCharging.getPileAdv.post(params).then(res => {
			const {
				objData,
				code
			} = res
			console.log(objData, code);
			if (code == 200) {
				var files = objData;
				allAdv.value = [];
				if (files != "" && files != null) {
					var fs = files.split(',');
					for (let i = 0; i < fs.length; i++) {
						var t = `${ config.static_URL }/adv/` + fs[i];
						allAdv.value[i] = t;
					}
				}
				console.log(allAdv);
			} else {
				// message.error($T('self.message.error'))
				message.error(err.msg);
			}
		}).catch(err => {
			message.error(err.msg);
		})
	}
	const OTA = (type) => {
		if (type.indexOf('ftp') != -1 && formState.value.ftp == "") {
			message.error($T('self.businessCharging.tips24'))
			return;
		}
		if (formState.value.pileSeri == "" || formState.value.stationId == "") {
			message.error($T('self.businessCharging.tips24'))
			return;
		}
		var params = {
			"id": formState.value.id,
			"stationId": formState.value.stationId,
			"ftp": formState.value.ftp,
			"type": type,
			"pileSeri": formState.value.pileSeri
		}
		console.log(params);
		$API.backend.businessCharging.OTA.post(params).then(res => {
			const {
				objData,
				code
			} = res
			console.log(objData, code);
			if (code == 200) {
				message.success($T('self.message.success'))
			} else {
				message.error(err.msg);
			}
		}).catch(err => {
			message.error(err.msg);
		})
	}
	// 子组件中要通过defineExpose将方法暴露给父组件
	defineExpose({
		add,
		edit,
	})
</script>

<style lang="scss" scoped>
	.edit-drawer {
		position: relative;

		.closeable {
			@include closeable;
		}
	}

	.del-box {
		position: absolute;
		right: 0px;
		top: 0px;
	}

	.del-box img {
		width: 20px;
		height: 20px;
		cursor: pointer;
		margin: 4px 0;
	}
</style>